﻿using System;
using System.Web.Mvc;

namespace OperationPlugins.Mvc.Filters
{
    /// <summary>
    /// Used to specify the <see cref="OperationId"/> for the current action method.
    /// 
    /// To use this, apply this attribute to an action method or to a controller class.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class CurrentOperationAttribute : FilterAttribute, IAuthorizationFilter
    {
        private readonly string _value;
        private OperationId _operation;

        /// <summary>
        /// Initializes a new instance of the CurrentOperationAttribute class.
        /// </summary>
        /// <param name="operationId">OperationId</param>
        public CurrentOperationAttribute(string operationId)
        {
            if (operationId == null)
            {
                throw new ArgumentNullException("operationId");
            }

            _value = operationId;
        }

        /// <summary>
        /// Gets the OperationId.
        /// </summary>
        public virtual string Value
        {
            get { return _value; }
        }

        /// <summary>
        /// Gets the OperationId.
        /// </summary>
        protected virtual OperationId Operation
        {
            get { return _operation ?? (_operation = new OperationId(Value)); }
        }

        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            OperationPluginsContext.Current.CurrentActionOperation = Operation;
        }

    }
}
